<template>
    <div class="box1">
        <div class="news">
            <div class="search">
                <el-input placeholder="搜索" class="input" v-model="search" :prefix-icon="Search" clearable
                    @focus="handleFocus" @blur="handleBlur" @clear="handleClear" />

                <el-tooltip class="box-item" effect="dark" content="该功能暂未开发" placement="bottom-end">
                    <el-button class="btn" :icon="Plus" size="small" />
                </el-tooltip>
            </div>
            <!-- 遍历 newsData 数据 -->
            <div v-if="flag">

                <div class="new" v-for="(item, index) in userChatStore.newsData" :key="index" @click="gotoChat(item)"
                    :class="{ selected: item.selected }">
                    <!-- 头像 -->
                    <el-badge :value="item.unreadCount" :max="99" class="item" :hidden="item.unreadCount === 0">

                        <div class="pic">
                            <img :src="item.senderId===userStore.userId?item.receiverAvatar:item.senderAvatar" alt="头像" />
                        </div>
                    </el-badge>
                    <!-- 名字和最后一条消息 -->
                    <div class="message-info">
                        <div class="name">{{item.senderId===userStore.userId? item.receiverName:item.senderName }}</div>
                        <div class="mes">{{ item.lastMessage }}</div>
                    </div>
                    <!-- 时间 -->
                    <div class="time">{{ item.timestamp }}</div>
                </div>

            </div>
            <el-scrollbar v-else>
                <div class="new" v-for="(item, index) in searchData" :key="index" @click="gotoChat(item)">


                </div>
            </el-scrollbar>
        </div>

        <div class="room">
            <router-view v-if="hasContent"></router-view>
            <div v-else class="no-content">
                <el-empty description="请选择好友" />
            </div>
        </div>


    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch } from 'vue';
import { Search, Plus } from '@element-plus/icons-vue';
import { useRouter, useRoute } from 'vue-router';

//引入用户相关的仓库,获取当前用户的头像、昵称
import useUserStore from '@/store/modules/user';
import useUserChatStore from '@/store/modules/userchat';
import io from 'socket.io-client';

let socket: any = null;
//获取存储用户信息的仓库对象
let userStore = useUserStore();
let userChatStore = useUserChatStore()
const hasContent = ref(false); // 用于判断 router-view 是否有内容

const router = useRouter();
const route = useRoute();
const searchData = reactive([])
// 存储搜索内容
let search = ref('');
let flag = ref(true);

// 获取输入框的引用
const inputBox = ref<any>();
const handleFocus = () => {
    flag.value = false;

}
// 连接到 WebSocket 服务器
socket = io('http://localhost:8080', {
    withCredentials: true
});

// 输入框失去焦点时隐藏清除按钮
const handleBlur = () => {
    if (search.value == '') {
        flag.value = true;
    } else {
        search.value = ''
    }

};
const handleClear = () => {
    flag.value = true;
    // 手动改变输入框的焦点状态
    inputBox.value?.blur();
}
// 打开聊天窗口
const gotoChat = (user: any) => {
    
    flag.value = true;
    const roomName=user._id
    console.log(user);
    let Id = ''
    if (user.senderId == userStore.userId) {
        Id = user.receiverId
    } else {
        Id = user.senderId
    }
    // 保存选中的好友ID到 localStorage
    localStorage.setItem('selectedFriendId', Id);
    // 通过id来设置当前聊天为选中状态
    userChatStore.updateSelection(Id)
    router.push({ name: 'ChatRoom', params: { id: Id ,roomName:roomName} });
}
// 获取与各个好友的最后一条信息和未读信息条数
const getChatLast = async () => {
    console.log('getChatLast', userStore.friendsList.map((friend:any) => friend.roomName));
    // 获取roomName数组
    const roomNames:string[]=userStore.friendsList.map((friend:any) => friend.roomName);

    userChatStore.friendsChat(userStore.userId as string,roomNames);
    const friendId = route.params.id;
    if (friendId) {
        userChatStore.updateSelection(friendId)
    }
}

const beforeRoute = async () => {
    console.log('beforeRoute');
    const activeTab = route.meta.activeTab;
    if (activeTab == 'chat') {
        hasContent.value = true;
    } else {
        hasContent.value = false;
    }
}
onMounted(async () => {
    await beforeRoute()
    await getChatLast()
    // 从 localStorage 获取选中的好友ID
    if (route.params.id) {
        const selectedFriendId = localStorage.getItem('selectedFriendId');
        console.log(selectedFriendId, '跳转了');
        if (selectedFriendId) {
            userChatStore.updateSelection(selectedFriendId);
        }
    } else {
        localStorage.removeItem('selectedFriendId')
    }
   
    // 监听聊天消息事件,有人给我发信息或者我发信息会触发
    // socket.on('chat message', (data: any) => {
    //     // 如果路由名不为ChatRoom，才执行
    //     const activeTab = route.meta.activeTab;
    //     console.log(222);
        
    //     // 聊天房间没有打开，自己获取最后一条聊天记录和未读信息条数
    //     if (activeTab !== 'chat') {
    //         if (data.msg.receiverId == userStore.userId) {
    //             userChatStore.friendsChat(userStore.userId as string)
    //         }
    //     }
    // });


})

watch(route, (newRoute) => {
    const newId = newRoute.params.id;
    if (newId) {
        hasContent.value = true; // 有有效的 friendId，显示聊天内容

    } else {
        hasContent.value = false; // 没有 friendId，显示请选择好友
    }
});


</script>

<style scoped lang="scss">
.box1 {
    display: flex;
    width: 100%;
    height: 100%;
    overflow: hidden;

    .news {
        width: 25%;
        height: 100vh;
        background: #f1f1f1;
        border-right: 1.5px solid #E0E0E0;

        .search {
            position: sticky;
            /* 固定在顶部 */
            top: 0;
            z-index: 10;
            /* 确保搜索框在最上层 */
            width: 100%;
            height: 70px;
            padding: 15px;
            background-color: #f1f1f1;
            display: flex;
            align-items: center;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

            /* 可选，增加阴影效果 */
            .input {
                width: 90%;
                height: 30px;
            }

            .btn {
                margin-left: 10px;
                width: 30px;
                height: 30px;

                &:hover {
                    background-color: #E0E0E0;
                    color: #333;
                }
            }
        }


        .new {
            height: 75px;
            width: 100%;
            overflow-y: auto;
            /* 使 news 容器能够滚动 */
            display: flex;
            align-items: center;
            background-color: #f1f1f1;
            padding: 15px;
            transition: background-color 0.3s ease;
            /* 平滑过渡效果 */

            &:hover {
                background-color: #E0E0E0;
                /* 鼠标悬停时的背景颜色 */
            }

            &.selected {
                /* 当某一条消息被选中时 */
                background-color: #d0d0d0;
                /* 更深的背景色 */
                box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
                /* 选中时的阴影效果 */
            }

            .item {
                width: 45px;
                height: 45px;

                .pic {
                    width: 45px;
                    height: 45px;
                    // border-radius: 50%;
                    overflow: hidden;
                    margin-right: 15px;

                    img {
                        width: 100%;
                        height: 100%;
                        object-fit: cover;
                    }

                }
            }

            .message-info {
                margin-left: 20px;
                flex-grow: 1;

                .name {
                    font-size: 16px;
                    font-weight: 500;
                    color: #333;
                }

                .mes {
                    font-size: 12px;
                    color: #888;
                    margin-top: 10px;
                }


            }

            .time {
                font-size: 12px;
                color: #aaa;
                margin-left: 10px;
            }
        }

    }

    .room {
        width: 75%;
        height: 100vh;

        .no-content {
            width: 100%;
            height: 100%;
            text-align: center;
            padding: 200px;
        }
    }
}
</style>